package com.scwatch.core.service.impl;


import com.scwatch.common.orm.Limitable;
import com.scwatch.common.orm.RowSide;
import com.scwatch.common.orm.SearchFilter;
import com.scwatch.core.domain.Chatroom;
import com.scwatch.core.repository.ChatroomDao;
import com.scwatch.core.service.ChatroomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service
@Transactional(readOnly = false, isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED)
public class ChatroomServiceImpl implements ChatroomService{
    public ChatroomServiceImpl() {
        super();
    }

    @Override
    public Page<Chatroom> findAll(Map<String, String[]> params, Pageable pageable) {
        return dao.findAll(spec(params),pageable);
    }

    @Override
    public RowSide<Chatroom> findSide(Map<String, String[]> params, Chatroom bean, Integer position, Sort sort) {
        if (position == null) {
            return new RowSide<Chatroom>();
        }
        Limitable limit = RowSide.limitable(position, sort);
        List<Chatroom> list = dao.findAll(spec(params), limit);
        return RowSide.create(list, bean);
    }

    @Override
    public List<Chatroom> getList() {
        return null;
    }

    @Override
    public Chatroom get(Integer id) {
        return dao.findOne(id);
    }

    @Override
    public String replace(String s) {
        return null;
    }

    @Override
    public Chatroom save(Chatroom bean) {
        bean = dao.save(bean);
        return bean;
    }

    @Override
    public Chatroom update(Chatroom bean) {
        bean = dao.save(bean);
        return bean;
    }

    @Override
    public Chatroom delete(Integer id) {
        Chatroom entity = dao.findOne(id);
        dao.delete(entity);
        return entity;
    }

    @Override
    public Chatroom[] delete(Integer[] ids) {
        Chatroom[] beans = new Chatroom[ids.length];
        for (int i = 0; i < ids.length; i++) {
            beans[i] = delete(ids[i]);
        }
        return beans;
    }

    private Specification<Chatroom> spec(Map<String, String[]> params) {
        Collection<SearchFilter> filters = SearchFilter.parse(params).values();
        Specification<Chatroom> sp = SearchFilter.spec(filters, Chatroom.class);
        return sp;
    }

    private ChatroomDao dao;
    @Autowired
    public void setDao(ChatroomDao dao){this.dao = dao;}
}
